package com.gitee.wsl.net.token

import io.ktor.http.HttpStatusCode
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.Route
import io.ktor.server.routing.post
import io.ktor.server.routing.route
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.hours

abstract class AbstractApiTokenServer {

    // AuthRoutes.kt
    fun Route.authRoutes() {
        route("/auth") {
            // 刷新Token接口
            post("/refresh") {
                val request = call.receive<RefreshRequest>()
                val refreshToken = request.refreshToken

                // 验证Refresh Token有效性
                val userId = validateRefreshToken(refreshToken)
                if (userId == null) {
                    call.respond(HttpStatusCode.Forbidden)
                    return@post
                }

                // 生成新Access Token
                val newAccessToken = generateAccessToken(userId)

                // 可选：生成新Refresh Token（轮转策略）
                val newRefreshToken = generateRefreshToken(userId)

                // 返回新Token
                call.respond(TokenResponse(newAccessToken, newRefreshToken))
            }
        }
    }

    abstract fun validateRefreshToken(refreshToken: String): String?

    abstract fun generateAccessToken(userId: String): String

    abstract fun generateRefreshToken(userId: String): String?

}

class RefreshRequest(val refreshToken: String)

data class TokenResponse(val accessToken: String, val refreshToken: String?)

// TokenUtils.kt
//object TokenUtils {
//    private val ACCESS_TOKEN_EXPIRY = 2.hours
//    private val REFRESH_TOKEN_EXPIRY = 7.days
//    private val SECRET = System.getenv("JWT_SECRET")
//
//    // 生成Access Token
//    fun generateAccessToken(userId: String): String {
//        return JWT.create()
//            .withSubject(userId)
//            .withExpiresAt(Date(System.currentTimeMillis() + ACCESS_TOKEN_EXPIRY.toMillis()))
//            .sign(Algorithm.HMAC256(SECRET))
//    }
//
//    // 验证Refresh Token
//    fun validateRefreshToken(token: String): String? {
//        return try {
//            val verifier = JWT.require(Algorithm.HMAC256(SECRET)).build()
//            verifier.verify(token).subject
//        } catch (e: Exception) {
//            null
//        }
//    }
//}